// APP
if (window.plus) {
    indexPageReady();
} else {
    document.addEventListener('plusready', indexPageReady, false);
}
// Web
$(function () {
    appConfig();
    if (AGENT_CLIENT.WEB) {
        indexPageReady();
    } else if (AGENT_CLIENT.APP) {
        $(".main").css("padding-bottom", "2px");
        $(".top").css("bottom", "10px");
        $("#wrapper").css('bottom', "0px");
        $("#scanlogo").show();
        document.addEventListener("netchange", function () {
            //获取当前网络类型
            var nt = plus.networkinfo.getCurrentType();
            // 联网状态
            if ([plus.networkinfo.CONNECTION_ETHERNET, plus.networkinfo.CONNECTION_WIFI, plus.networkinfo.CONNECTION_CELL2G, plus.networkinfo.CONNECTION_CELL3G, plus.networkinfo.CONNECTION_CELL4G].indexOf(nt) > -1) {
                $("#nonetworkinfo").hide();
                plus.webview.currentWebview().reload();
            } else {
                $("#nonetworkinfo").show();
            }
        }, false);
    }
});

// app设置
function appConfig() {
    // 如果是客户端跳转到官网
    //if (JSON.stringify(os) == "{}") {
    //    window.location.href = "http://www.soolife.cn";
    //    return;
    //}


    // 清空缓存1天数据
    var storageTime = getLocalStorage(STORAGE_MANAGER.storeageTime);
    var nowtime = new Date(new Date().Format("yyyy-MM-dd")).getTime();
    if (!storageTime || nowtime > storageTime) {
        removeLocalStorage(STORAGE_MANAGER.category);
        removeLocalStorage(STORAGE_MANAGER.parentcategory);
        setLocalStorage(STORAGE_MANAGER.storeageTime, nowtime);
    }

    // 获取IP地址
    $.getIPAddress(true);
}

// 初始化方法
function indexPageReady() {
    var _conentheight = ($(window).height() - CONFIG_MANAGER.headerHight);
    var _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
    var _docMain = ("fixed" == $(".main").css("position")) ? $(".main") : $(window);
    var _showDownload = AGENT_CLIENT.WEB;
    // IScroll
    // _loadingStep: 加载状态0默认，1显示加载状态，2执行加载数据，只有当为0时才能再次加载，这是防止过快拉动刷新
    var _myScroll, _pullDownEl, _pullDownL, _pagecount = 1, _loadingStep = 0;
    var indexPage = function () {
        this.init();
    };
    indexPage.prototype = {
        // 初始化
        init: function () {
            this.initIscroll();
            this.paintDownload();
            this.loadads(true);
            this.loadSearchTag();
            this.loadNewsData();
            this.bindEvent();
        },
        // 获取广告
        loadads: function (firstload) {
            var model = this;
            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/ads/locatins/[APP-Home]"
            }).done(function (res) {
            	$("#nonetworkinfo").hide();
                if (res) {
                    model.paintPage(res);
                }
            }).fail(function (res) {
                if (firstload) {
                    setTimeout(function () {
                        //$.toast(ERROR_MESSAGE.network);
                        $("#nonetworkinfo").show();
                    }, 1500);
                } else {
                    //$.toast(ERROR_MESSAGE.network);
                    $("#nonetworkinfo").show();
                }

            });
        },
        // 画页面
        paintPage: function (adslocatins) {
            this.setAdsImg(adslocatins);
            this.loadSoo();
        },
        // 下载页面
        paintDownload: function () {
            var thispage = this;
            if (AGENT_CLIENT.APP) {
                return;
            }

            var isShowDown = sessionStorage.getItem(STORAGE_MANAGER.is_show_download_div);
            _showDownload = (!isShowDown || isShowDown == "true") ? true : false;
            if (!_showDownload) {
                return;
            }

            // 显示现在浮层
            thispage.displayDownloadDiv(true);
            // 关闭浮层
            $("#btnCloseDownload").on("click", function () {
                _showDownload = false;
                thispage.displayDownloadDiv(false);
            });
            // 跳转下载APP地址
            $("#btndownload").on("click", function () {
                var downloadUrl = "";
                // 判断IOS/Andriod
                if (os.ios) {
                    // APPStore 下载地址
                    downloadUrl = "https://itunes.apple.com/us/app/ru-ci-sheng-huo/id1066576666?mt=8";
                } else {
                    // Andriod 下载地址
                    downloadUrl = "http://wap.soolife.cn/download/soolife.apk";
                }
                window.open(downloadUrl);
            });
        },
        // 显示下载浮层
        displayDownloadDiv: function (isdisplay) {
            if (isdisplay) {
                sessionStorage.setItem(STORAGE_MANAGER.is_close_download_div, false);
                $("#downloadBox").show();
                $("#wrapper").css("top", "90px");
                _myScroll.refresh();
            } else {
                sessionStorage.setItem(STORAGE_MANAGER.is_close_download_div, true);
                $("#downloadBox").hide();
                $("#wrapper").css("top", "45px");
                _myScroll.refresh();
            }
        },
        // 设置首页广告图
        setAdsImg: function (locatins) {
            // 设置滚动广告
            var adslist = locatins["E0--1"];
            var bannerhtml = [];
            $.each(adslist, function (i, item) {
                var imgsrc = getImageUrl(item.path, 1080, 540);
                bannerhtml.push("<li><img src='" + imgsrc + "'    link='" + item.link + "' size='1080*540'></li>");
            });
            $(".slider ul").html(bannerhtml.join(""));
            // 轮播图
            $(".slider").touchSlider({
                width: $(window).width(),
                height: $(window).width() * 0.5013,
                during: 3000,
                autoplay: true,
                defaultimage: $("#defaultbannerimage")
            });
            // 设置其他图片
            var adsimglist = $("img[id^=adsE]");
            for (var i = 0; i < adsimglist.length; i++) {
                var adsimg = $(adsimglist[i]);
                var id = adsimg.attr("id");
                var tag = id.substr(3);
                var urllist = locatins[tag];
                if (!urllist) {
                    return;
                }
                var imgsrc = (urllist.length > 0) ? urllist[0].path : "../../images/grey.gif";
                var imglink = (urllist.length > 0) ? urllist[0].link : "";
                // 获取图片尺寸
                var imgwidth = 114,
                    imgheight = 114;
                var sizestr = adsimg.attr("size");
                if (sizestr) {
                    var size = sizestr.split('*');
                    if (size.length == 2) {
                        imgwidth = size[0];
                        imgheight = size[1];
                    }
                }
                adsimg.attr({
                    "data-original": getImageUrl(imgsrc, imgwidth, imgheight),
                    link: imglink
                });
            }
            var shophtml = [];
            var e51 = locatins["E5--1"],
                e52 = locatins["E5--2"],
                e53 = locatins["E5--3"];
            var mksxdpwidth = $(window).width() * 0.67;
            $.each(e51, function (i, item) {
                var img2 = (e52.length > i) ? e52[i] : {
                    path: "",
                    link: ""
                };
                var img3 = (e53.length > i) ? e53[i] : {
                    path: "",
                    link: ""
                };
                shophtml.push("<div class='mksxdp' style='width: " + mksxdpwidth + "px'>");
                shophtml.push("<p class='syxdp1 mbboder'><a><img class='lazy'  src='../../images/place/439x460.png'  data-original='" + getImageUrl(item.path, 439, 460) + "' link='" + item.link + "'></a></p>");
                shophtml.push("<p class='syxdp2'>");
                shophtml.push("<span><a><img  class='lazy'  src='../../images/place/181x220.png'  data-original='" + getImageUrl(img2.path, 181, 220) + "'  link='" + img2.link + "'></a></span>");
                shophtml.push("<span class='margin5'><a><img class='lazy' src='../../images/place/181x220.png'  data-original='" + getImageUrl(img3.path, 181, 220) + "'  link='" + img3.link + "'></a></span>");
                shophtml.push("</p></div>");
            })

            var hotshopwidth = e51.length * (mksxdpwidth + 12);
            $("#hotshopwrapper").height(mksxdpwidth - 55); // 计算wrapper高度
            $("#hotshopscroller").width(hotshopwidth);
            $("#hotshoplistdiv").width(hotshopwidth).html(shophtml.join(""));
            var hotshopScroll = new IScroll('#hotshopwrapper', {scrollX: true, scrollY: false, mouseWheel: true});
            // 懒加载
            $('img.lazy').lazyload({
                event: "scroll",
                threshold: 100,
                failure_limit: 10
            });
            $('img.lazy').lazyload({
                event: "scroll",
                threshold: 100,
                container: $(".main"),
                failure_limit: 10
            });
        },
        // SOO快报
        loadSoo: function () {
            // Soo快报
            var _notice_count = 0,
                _notice_count_i = 0,
                _notice_isdesc = false,
                _notice_isfirst = true;
            var postdata = {
                index: 1,
                size: 10,
                search: {
                    type: 1
                }
            };
            $.ajax({
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/news/lists"
            }).done(function (res) {
                var response = JSON.parse(res);
                var html = [];
                $.each(response.data, function (i, item) {
                    html.push("<li><a>" + item.content + "<span class='rejian'></span></a></li>");
                });
                $("#noticelist").html(html.join(""));
                _notice_count = response.data.length;
                var notice = setInterval(notice, 3000);
                // Soo快报
                function notice() {
                    if (_notice_count == 1) {
                        return;
                    }
                    // 第一次滚动
                    if (_notice_isfirst) {
                        _notice_count_i++;
                        _notice_isfirst = false;
                    }
                    $('#noticelist').animate({
                        'margin-top': '-' + (40 * _notice_count_i) + 'px'
                    }, 500);
                    if (_notice_count_i == (_notice_count - 1)) {
                        _notice_isdesc = true;
                    } else if (_notice_count_i == 0) {
                        _notice_isdesc = false;
                    }
                    if (_notice_isdesc) {
                        _notice_count_i--;
                    } else {
                        _notice_count_i++;
                    }
                }
            });
        },
        // 绑定事件
        bindEvent: function () {
            var model = this;
            // 置顶
            $("#gotop").on("click", function () {
                _myScroll.scrollTo(0, 0, 800);
            });

            // 扫一扫
            $("#btnscan").on("click", function () {
                redirect("../barcode/barcodescan.html", false, "pop-in", function () {
                    if (os.ios) {
                        plus.navigator.setStatusBarBackground("rgba(0,0,0,0.97)");
                        plus.navigator.setStatusBarStyle('UIStatusBarStyleBlackOpaque');
                    }
                });
            });
            // 跳转消息页
            $("#btnmsg").on("click", function () {
                redirect("../message/messagelist.html", false, "pop-in", function () {
                    $("#btnmsg p").removeClass();
                });
            });
            // 跳转搜索页
            $("#indexsearch").on("click", function () {
                showSearchPage();
            });
            // 猜你喜欢
            $("#loveitemlist").on("click", "li", function () {
                redirect("../goods/goodsdetail.html?id=" + $(this).attr("tip"));
            });
            //跳转页面
            $("#ul_nav>li").on("click", function () {
                var jumpUrl = $(this).attr("tip");
                _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
                var loginedMember = getLocalStorage(STORAGE_MANAGER.currentmember);
                if (/selectRechargeAmount\.html|orders\.html|invite\.html|attention\.html/.test(jumpUrl)) {
								  if (!_currentloginuser) {
                    //用户若无登录，必须登录
                    var redirectUrl = "../account/login.html?backurl=" + jumpUrl.replace("../", "").replace("/", "|") + "&fromurl=" + "home|index.html";
                    redirect( redirectUrl );
                    return;
                  }
                }
                //全民商谈，惠赚钱
                else if((/apply\.html|sign\.html/.test(jumpUrl))){
                  if(_currentloginuser && loginedMember.phone){
                    if(/apply\.html/.test(jumpUrl)){	                    	
                    	if(loginedMember.is_agent){
                    		redirect("../merchant/select.html");
                    		return;
                    	}
                    }else if(/sign\.html/.test(jumpUrl)){
                    	if(loginedMember.is_makemoney){
                    		redirect("../earnmoney/earnmoney.html");
                    		return;
                    	}
                    }
                  }                	
                }
                //领星币
                else if (/coinlist\.html/.test(jumpUrl)) {
                  // 领星币
                  if (AGENT_CLIENT.APP) {
                      plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(2)");
                  } else {
                      redirect("../coin/coinlist.html")
                  }
                  return;
                } 
                //商品分类
                else if (/classification\.html/.test(jumpUrl)) {
                  // 领星币
                  if (AGENT_CLIENT.APP) {
                      plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(1)");
                  } else {
                      redirect("../home/classification.html")
                  }
                  return;
                }
                redirect(jumpUrl);
            });
            // 点击图片
            $("img[id^=adsE]").on("click", function () {
                adsRedirect(this);
            });
            // 滚动广告
            $(".slider").on("click", "img", function () {
                adsRedirect(this);
            });
            // 星店铺
            $("#hotshoplistdiv").on("click", "img", function () {
                adsRedirect(this);
            });

            function adsRedirect(adsimg) {
                var link = $(adsimg).attr("link");
                if (link) {
                    if (link.indexOf("http") > -1) {
                        redirect(link);
                    } else {
                        redirect("../" + link);
                    }
                }
            }

            // 跳转星粉星币
            $("#btncoin").on("click", function () {
                // 领星币
                if (AGENT_CLIENT.APP) {
                    plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(2)");
                } else {
                    redirect("../coin/coinlist.html")
                }
            });
        },
        // 搜索框中随机显示二级分类
        loadSearchTag: function () {
            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/goods/search/tag/1"
            }).done(function (res) {
                if (res && res.length > 0) {
                    var catagory = res[0];
                    $("#indexsearch p").text(catagory.name).attr("tip", catagory.catagory_no);
                    setLocalStorage(STORAGE_MANAGER.searchtag, {
                        catagory_no: catagory.catagory_no,
                        name: catagory.name
                    });
                }
            });
        },
        // 猜你喜欢
        loadloveitemlist: function () {
            var uid = (_currentloginuser) ? _currentloginuser.id : getSessionID();
            $.ajax({
                type: 'GET',
                url: CONFIG_MANAGER.RequstUrl + "v1/goods/rank/like/" + uid + "/" + 6,
                beforeSend: function () {
                    $.showWaiting();
                }
            }).done(function (res) {
            	$("#nonetworkinfo").hide();
                if (!res || res.length == 0) {
                    return;
                }
                var html = [];
                $.each(res, function (i, goodsitem) {
                    html.push("<li class='syxhd' tip='" + goodsitem.sku_id + "'><dl><dt><img class='lazy' data-original='" + getImageUrl(goodsitem.logo, 500, 500) + "' src='../../images/place/500x500.png'></dt><dd>" + goodsitem.name + goodsitem.title + "</dd><dd class='xhmony'>￥" + goodsitem.shop_price + "</dd></dl></li>");
                });
                $("#loveitemlist").html(html.join(""));
                _myScroll.refresh();
                // 懒加载
                $('img.lazy').lazyload({
                    placeholder: "../../images/white.gif",
                    container: "#loveitemlist",
                    event: "scroll",
                    threshold: 100,
                    failure_limit: 10
                });
                _myScroll.scrollToElement(".cnxhdbiaoti", 800);
            }).fail(function (res) {
                //$.toast(ERROR_MESSAGE.network);
                $("#nonetworkinfo").show();
            }).always(function (res) {
                $.closeWaiting();
            });
        },
        // 加载公告消息
        loadNewsData: function () {
            // 3.新闻播报 4.促销活动
            var postdata = {
                index: 1,
                size: 20,
                search: {
                    type: "3|4"
                },
                sorting: {
                    time: "DESC"
                }
            };
            $.ajax({
                headers: {
                    'Content-Type': 'application/json'
                },
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/news/lists",
                data: JSON.stringify(postdata)
            }).done(function (res) {
                var newslist = JSON.parse(res).data;
                if (newslist && newslist.length > 0) {
                    var create_time = new Date(toDateString(newslist[0].create_time, "yyyy-MM-dd hh:mm:ss")).getTime();
                    // 最后查看日期
                    var lastCheckTime = getLocalStorage(STORAGE_MANAGER.lastCheckTime);
                    // 有新消息
                    if (!lastCheckTime || (lastCheckTime < create_time)) {
                        $("#btnmsg p")[0].className = "hquan";
                    }
                }
            });
        },
        // 判断显示置顶图标
        isDisplayTopIcon: function (y) {
            var top = (y * -1);
            if (top > _conentheight / 2) {
                $('#gotop').show();
            } else {
                $('#gotop').hide();
            }
        },
        // 初始化Iscroll
        initIscroll: function () {
            var thisPage = this;
            _pullDownEl = $('#pullDown');
            _pullDownL = _pullDownEl.find('.pullDownLabel');

            _myScroll = new IScroll('#wrapper', {
                probeType: 2,
                scrollbars: true,
                mouseWheel: false,
                fadeScrollbars: true,
                bounce: true,
                interactiveScrollbars: false,
                click: true,
                disableMouse: true,
                disablePointer: true
            });


            var hasInitLoveItemList = false,
                totopheight = $("#loveitemlist").offset().top;
            //滚动时
            _myScroll.on('scroll', function () {
                if (_loadingStep == 0 && !_pullDownEl.attr('class').match('flip|loading')) {
                    if (this.y > 5) {
                        //下拉刷新效果
                        _pullDownEl.attr('class', "flip")
                        _pullDownEl.show();
                        _myScroll.refresh();
                        _pullDownEl.addClass('flip');
                        _pullDownL.html('松开刷新');
                        _loadingStep = 1;
                    }
                }

                // 判断是否显示下载浮层
                if (_showDownload) {
                    if (this.y < -100) {
                        thisPage.displayDownloadDiv(false);
                    } else {
                        thisPage.displayDownloadDiv(true);
                    }
                }
            });


            //滚动完毕
            _myScroll.on('scrollEnd', function () {
                if (_loadingStep == 1) {
                    if (_pullDownEl.attr('class').match('flip|loading')) {
                        _pullDownEl.removeClass('flip').addClass('loading');
                        _pullDownL.html('正在刷新...');
                        _loadingStep = 2;
                        pullDownAction();
                    }
                }

                // 加载猜你喜欢
                if (!hasInitLoveItemList) {
                    if ($("#loveitemlist").offset().top <= $(window).height() + 10) {
                        hasInitLoveItemList = true;
                        thisPage.loadloveitemlist();
                    }
                }

                // 判断是否显示置顶
                thisPage.isDisplayTopIcon(this.y);

                // 判断是否显示下载浮层
                if (_showDownload) {
                    if (this.y < -100) {
                        thisPage.displayDownloadDiv(false);
                    } else {
                        thisPage.displayDownloadDiv(true);
                    }
                }

                // 懒加载
                $('img.lazy').lazyload({
                    container: $("#wrapper"),
                    threshold: 100,
                    failure_limit: 10
                });

                _myScroll.refresh();
            });

            // 下拉刷新
            function pullDownAction() {
                setTimeout(function () {
                    _pagecount = _pagecount + 1;
                    refreshPage();
                    _pullDownEl.hide();
                    _pullDownEl.removeClass('loading');
                    _pullDownL.html('下拉刷新');
                    _myScroll.refresh();
                    _loadingStep = 0;
                }, 1000);
            }

            // 刷新页面
            function refreshPage() {
                $(".focus").remove()
                var adsimglist = $("img[id^=adsE]");
                for (var i = 0; i < adsimglist.length; i++) {
                    var adsimg = $(adsimglist[i]);
                    // 获取图片尺寸
                    var imgwidth = 114,
                        imgheight = 114;
                    var sizestr = adsimg.attr("size");
                    if (sizestr) {
                        var size = sizestr.split('*');
                        if (size.length == 2) {
                            imgwidth = size[0];
                            imgheight = size[1];
                        }
                    }
                    adsimg.attr({
                        "src": "../../images/place/" + imgwidth + "x" + imgheight + ".png"
                    });
                }

                thisPage.loadads();
            }

            document.addEventListener('touchmove', function (e) {
                e.preventDefault();
            }, false);
        }
    };
    var _indexPage = new indexPage();
}

// 显示搜索页
function showSearchPage() {
    $("#searchiframe").show();
    searchiframe.window.show($("#indexsearch p").text());
    searchiframe.window.loadSearchHistory();
}

// 关闭搜索页
function closeSearchPage() {
    $("#searchiframe").hide();
}
// 重写搜索页
function search(searchword) {
};

//  触发当前页
function activePage() {

}